package cn.tradewin.advisor.pages.master;

import java.util.List;

import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.slf4j.Logger;

import cn.tradewin.advisor.commons.model.WeekDay;
import cn.tradewin.advisor.commons.selectmodel.CodeLabelSelectModel;
import cn.tradewin.advisor.commons.util.CalendarCategorySymbols;
import cn.tradewin.advisor.commons.util.CalendarUtil;
import cn.tradewin.advisor.commons.util.CodeTableSymbols;
import cn.tradewin.advisor.commons.util.LanguageSymbols;
import cn.tradewin.advisor.persist.model.Advcalendar;
import cn.tradewin.advisor.persist.model.CalendarDates;
import cn.tradewin.advisor.persist.services.CalendarService;
import cn.tradewin.advisor.persist.services.CodetableService;

public class CalendarAdd {
	
	@Inject
	private Logger log;
	
	@Property
	private Advcalendar calendar;

	@Property
	private String category;
	
	@Property
	private CodeLabelSelectModel categoryModel;
	
	@Property
	private CodeLabelSelectModel localeSelectModel;
	
	@Inject
	private CodetableService codetableService;
	
	
	@Inject
	private CalendarService calendarService;
	
	void setupRender() {
		localeSelectModel = new CodeLabelSelectModel(codetableService.listCategory(CodeTableSymbols.COUNTRY_TYPE, LanguageSymbols.ZH));
		categoryModel = new CodeLabelSelectModel(calendarService.getCalendarCategory(LanguageSymbols.ZH));
	}
	
	
	void onPrepare() {
		if (calendar == null) {
			calendar = new Advcalendar();
		}
	}
		
	Object onSuccess() {
		List<WeekDay> weekends = CalendarUtil.getAllWeekendDays(calendar.getYear(), CalendarUtil.DEFAULT_PATTERN);
		List<CalendarDates> dates = CollectionFactory.newList();
		for (WeekDay date : weekends) {
			CalendarDates d = new CalendarDates();
			d.setCalendarId(calendar.getId());
			if (date.getWeekday() == 6) {
				d.setCategoryId(new Integer(CalendarCategorySymbols.SATURDAY).byteValue());
			} else {
				d.setCategoryId(new Integer(CalendarCategorySymbols.SUNDAY).byteValue());
			}
			d.setDate(date.getDate());
			d.setStartTime(calendar.getStartTime());
			d.setEndTime(calendar.getEndTime());
			dates.add(d);
		}
		calendarService.addCalendarWithWeekend(calendar, dates);
		return Calendar.class;
	}
}